<template>
  <div class="caijizhan flex">
    <left2></left2>

    <div style="width: calc(100vw - 220px); height: 100vh; overflow: auto;" class="animate__animated animate__fadeIn">
      <div class="flexc" style="padding: 30px 30px 0;">
        <el-button type="primary" icon="el-icon-plus" @click="logshow">添加采集站</el-button>
        <el-button type="primary" icon="el-icon-upload2" @click="batch=true">批量执行</el-button>
        <el-button type="primary" icon="el-icon-download" @click="downloadCompile">下载excel模版</el-button>
      </div>
      <div class="flexc" style="padding:30px;">
        <div><el-input v-model="search.param.ip" style="width: 200px; margin-right: 20px;"
            placeholder="请输入采集站ip" clearable></el-input></div>
        <el-button type="primary" @click="searchgo()">检索</el-button>
      </div>
      <div style="padding:0 30px;">
        <el-table :data="list" style="width: 100%;">
          <el-table-column align="center" prop="collectionId" label="采集站id"></el-table-column>
          <el-table-column align="center" prop="ip" label="采集站ip"></el-table-column>
          <el-table-column align="center" prop="port" label="采集站端口"></el-table-column>
          <el-table-column align="center" prop="lastSuccessDate" label="上次成功时间"></el-table-column>
          <el-table-column align="center" prop="lastSuccessFileName" label="上次成功文件名"></el-table-column>
          <el-table-column align="center" prop="lastSuccessFilePath" label="上次成功的文件地址"></el-table-column>
          <el-table-column align="center" prop="onlineStateStr" label="当前状态"></el-table-column>
          <el-table-column align="center" prop="createdDate" label="创建时间"></el-table-column>
          <el-table-column align="center" label="操作" width="300px">
            <template slot-scope="scope">
              <div class="flexcc">
                <div style="color: #0093F6; cursor: pointer; margin: 0 10px;" @click="chakan(scope.row,1)">查看参数</div>
<!--                 <div style="color: #0093F6; cursor: pointer; margin: 0 10px;" @click="chakan(scope.row,2)">新参数设置</div> -->
                <div style="color: #0093F6; cursor: pointer; margin: 0 10px;" @click="bianji(scope.row)">修改</div>
                <div style="color: #f00; cursor: pointer; margin: 0 10px;" @click="shanchu(scope.row)">删除</div>

                <el-upload class="avatar-uploader" action="#" :on-change="(file, fileList) => {uploadok(file, fileList, scope.row)}" :auto-upload="false" :show-file-list="false">
                  <div style="color: #0093F6; cursor: pointer; margin: 0 10px;">执行</div>
                </el-upload>

                <div style="color: #0093F6; cursor: pointer; margin: 0 10px;" @click="getzhixinglishi(scope.row)">执行历史</div>
              </div>
            </template>
          </el-table-column>
        </el-table>

        <el-pagination style="padding: 20px; text-align: right;" @current-change="fanye" background
          :page-size="search.size" layout="total,prev, pager, next" :total="total">
        </el-pagination>
      </div>
    </div>
    <el-dialog title="批量执行" center :visible.sync="batch" width="600px"  :close-on-click-modal="false" :close-on-press-escape="false" :modal-append-to-body="true">
        <!-- Excel文件上传区域 -->
        <el-upload
          class="upload-excel"
          :auto-upload="false"
          :file-list="excelFileList"
          :on-change="handleExcelChange"
          :before-upload="beforeExcelUpload"
          accept=".xlsx,.xls"
          action=""
        >
        <el-button size="small" type="primary">选择Excel文件</el-button>
        <div slot="tip" class="el-upload__tip">
          请选择.xlsx/.xls格式文件，不超过5MB
        </div>
        </el-upload>

        <el-upload
          class="upload-json"
          :auto-upload="false"
          :file-list="jsonFileList"
          :on-change="handleJsonChange"
          :before-upload="beforeJsonUpload"
          accept=".txt"
          action=""
        >
        <el-button size="small" type="primary" style="margin-top: 20px;">选择JSON文件</el-button>
        <div slot="tip" class="el-upload__tip">
          请选择json文件，不超过5MB
        </div>
        </el-upload>

        <!-- 统一提交按钮 -->
        <el-button
          type="success"
          style="margin-top: 15px;"
          @click="submitFiles"
          :disabled="!excelFile || !jsonFile"
        >
          提交文件
        </el-button>
    </el-dialog>

    <el-dialog :title="logtitle" center :visible.sync="log" width="600px"  :close-on-click-modal="false" :close-on-press-escape="false" :modal-append-to-body="true">
        <div><el-input v-model="all.ip" style="width: 100%; margin-bottom: 30px;" placeholder="请输入ip"></el-input></div>
        <div><el-input v-model="all.port" style="width: 100%; " placeholder="请输入端口号"></el-input></div>

    	  <span slot="footer" class="dialog-footer">
          <el-button type="danger" round @click="log = false">取消</el-button>
          <el-button type="danger" round @click="add">确定</el-button>
    	  </span>
    </el-dialog>

    <el-dialog title="查看" center :visible.sync="caijizhanpeilog" width="600px"  :close-on-click-modal="false" :close-on-press-escape="false" :modal-append-to-body="true">
        <div><el-input v-model="caijizhanpeizhiall.ip" style="width: 100%; margin-bottom: 30px;" placeholder="请输入ip"></el-input></div>
        <div><el-input v-model="caijizhanpeizhiall.port" style="width: 100%; " placeholder="请输入端口号"></el-input></div>

    	  <span slot="footer" class="dialog-footer">
          <el-button type="danger" round @click="log = false">取消</el-button>
          <el-button type="danger" round @click="add">确定</el-button>
    	  </span>
    </el-dialog>

    <el-dialog title="执行历史" center :visible.sync="log2" width="1000px"  :close-on-click-modal="false" :close-on-press-escape="false" :modal-append-to-body="true">
        <el-table :data="zhixinglishilist" style="width: 100%;">
          <el-table-column align="center" prop="ip" label="ip"></el-table-column>
          <el-table-column align="center" prop="port" label="端口号"></el-table-column>
          <el-table-column align="center" prop="lastDate" label="执行时间"></el-table-column>
          <el-table-column align="center" prop="lastFileName" label="执行文件名"></el-table-column>
          <el-table-column align="center" prop="lastFilePath" label="执行文件存储地址"></el-table-column>
          <el-table-column align="center" prop="lastResult" label="结果">
            <template slot-scope="scope">
              <div v-if="scope.row.lastResult == true">成功</div>
              <div v-if="scope.row.lastResult == false">失败</div>
            </template>
          </el-table-column>
        </el-table>

    	  <span slot="footer" class="dialog-footer">
          <el-button type="danger" round @click="log2 = false">确定</el-button>
    	  </span>
    </el-dialog>

  </div>
</template>

<script>
import {
  addstations,
  removestations,
  updatestations,
  zhixinBatch,
  getstationsall,
  zhixingid,
  zhixinglishi
} from '@/api/caijizhanxin.js'
import left2 from '@/view/left2.vue'
import {exportDefault} from '../../api/caijizhanxin'
export default {
  name: 'caijizhanxin',
  components: {
    left2
  },
  data () {
    return {
      caijizhanpeizhiall: '',
      caijizhanpeilog: false,
      all: {
        ip: '',
        port: '',
        collectionId: ''
      },
      list: [],
      search: {
        'page': 1,
        'size': 10,
        'param': {
          'ip': '',
          'stationsNo': ''
        }
      },
      total: 0,
      excelFile: null, // 存储选中的Excel文件
      jsonFile: null, // 存储选中的JSON文件
      excelFileList: [], // Excel文件列表（用于组件显示）
      jsonFileList: [], // JSON文件列表（用于组件显示）
      log: false,
      log2: false,
      batch: false,
      zhixinglishilist: [],
      logtitle: ''

    }
  },
  created () {
    this.getlist()
  },
  mounted () {

  },
  methods: {
    // 处理Excel文件选择
    handleExcelChange (file, fileList) {
      // 只保留最新选择的一个文件
      this.excelFileList = fileList.slice(-1)
      this.excelFile = this.excelFileList[0] ? this.excelFileList[0].raw : null
    },

    // 处理JSON文件选择
    handleJsonChange (file, fileList) {
      // 只保留最新选择的一个文件
      this.jsonFileList = fileList.slice(-1)
      this.jsonFile = this.jsonFileList[0] ? this.jsonFileList[0].raw : null
    },

    // Excel文件校验
    beforeExcelUpload (file) {
      const isExcel = file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' ||
          file.type === 'application/vnd.ms-excel'
      const isLt5M = file.size / 1024 / 1024 < 5

      if (!isExcel) {
        this.$message.error('只能上传Excel文件（.xlsx/.xls）！')
        return false
      }
      if (!isLt5M) {
        this.$message.error('Excel文件大小不能超过5MB！')
        return false
      }
      return true
    },

    // JSON文件校验
    beforeJsonUpload (file) {
      const isLt5M = file.size / 1024 / 1024 < 5

      if (!isLt5M) {
        this.$message.error('JSON文件大小不能超过5MB！')
        return false
      }
      return true
    },

    // 提交文件到后台
    async submitFiles () {
      // 再次校验确保文件有效
      if (!this.excelFile || !this.beforeExcelUpload(this.excelFile)) {
        this.$message.warning('请先选择有效的Excel文件')
        return
      }
      if (!this.jsonFile || !this.beforeJsonUpload(this.jsonFile)) {
        this.$message.warning('请先选择有效的JSON文件')
        return
      }

      // 创建FormData对象，按固定顺序添加文件
      const formData = new FormData()
      // 第一个参数是后台接收的参数名，确保和后端约定一致
      formData.append('excel', this.excelFile) // 明确标记为excel文件
      formData.append('file', this.jsonFile) // 明确标记为json文件

      try {
        this.$message.loading({ message: '文件上传中...', duration: 0 })
        const response = await zhixinBatch(formData)

        if (response.data.code === 200) {
          this.$message.success('文件上传成功！')
          // 清空选择
          this.excelFileList = []
          this.jsonFileList = []
          this.excelFile = null
          this.jsonFile = null
        } else {
          this.$message.error(`上传失败：${response.data.message || '未知错误'}`)
        }
      } catch (error) {
        console.error('上传错误：', error)
        this.$message.error('文件上传失败，请重试')
      }
    },
    // 下载附件
    downloadCompile () {
      exportDefault().then((res) => {
        const blob = new Blob([res], {
          type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
        })
        var downloadElement = document.createElement('a')
        var href = window.URL.createObjectURL(blob)
        downloadElement.href = href
        downloadElement.download = '批量导入下载模版.xlsx'
        document.body.appendChild(downloadElement)
        downloadElement.click()
        document.body.removeChild(downloadElement)
        window.URL.revokeObjectURL(href)
      })
    },
    uploadok: function (file, fileList, item) {
      let obj = new FormData()
      obj.append('file', file.raw)
      zhixingid(item.collectionId, obj).then((response) => {
        this.$message.success('执行成功')
        this.getlist()
      })
    },
    getzhixinglishi: function (item) {
      zhixinglishi(item.collectionId).then((response) => {
        this.zhixinglishilist = response.data
        this.log2 = true
      })
    },
    zhixing: function (item) {
      // this.$confirm('此操作将永久删除, 是否继续?', '提示', {
      //   confirmButtonText: '确定',
      //   cancelButtonText: '取消',
      //   type: 'warning'
      // }).then(() => {
      //   zhixingid(item.collectionId).then((response) => {
      //     this.$message.success('执行成功');
      //     this.getlist()
      //   })
      // })
    },

    chakan: function (item, chakan) {
      const newRoute = this.$router.resolve({
        path: '/caijizhanxin/chakan',
        query: {
          collectionId: item.collectionId,
          chakan: chakan
        }
      })
      window.open(newRoute.href, '_blank')

      // this.$router.push({
      //   path:'/caijizhanxin/chakan',
      //   query:{
      //     collectionId:item.collectionId,
      //     chakan:true
      //   }
      // })
    },

    shanchu: function (item) {
      this.$confirm('此操作将永久删除, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        removestations(item.collectionId).then((response) => {
          this.$message.success('删除成功')
          this.getlist()
        })
      })
    },

    bianji: function (item) {
      this.all = {
        ip: item.ip,
        port: item.port,
        collectionId: item.collectionId
      }
      this.logtitle = '修改采集器'
      this.log = true
    },

    logshow: function () {
      this.all = {
        ip: '',
        port: ''
      }
      this.logtitle = '新增采集站'
      this.log = true
    },

    add: function () {
      if (this.all.collectionId) {
        updatestations(this.all).then((response) => {
          this.$message.success('修改成功')
          this.log = false
          this.getlist()
        })
      } else {
        addstations(this.all).then((response) => {
          this.$message.success('新增成功')
          this.log = false
          this.getlist()
        })
      }
    },

    searchgo: function () {
      this.search.page = 1
      this.getlist()
    },

    getlist: function () {
      getstationsall(this.search).then((response) => {
        this.list = response.data.result
        this.total = response.data.count
      })
    },

    fanye: function (val) {
      this.search.page = val
      this.getlist()
    }

  }
}
</script>

<style scoped>

</style>
